<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Librarys\AppUtil;

class NetPayController extends Controller
{
    private $productTable = 'products';

    private $paymentOrderTable = 'payment_orders';

    private $status = 1;

    private $returl = '/api/netPay_ret'; //同步通知地址

    private $notifyurl = '/api/netPay_notify'; //异步通知地址

    public function __invoke(Request $request, $userId, $productId)
    {
        $product = DB::table($this->productTable)->where('id', $productId)->first();
        if (empty($product) || empty($userId)) {
            return;
        }

        $paymentOrderData = [
            'product_name' => $product->product_name,
            'procuct_price' => $product->procuct_price,
            'order_price' => $product->procuct_price,
            'status' => $this->status,
            'user_id' => $userId,
            'created_at' => date("Y-m-d H:i:s")
        ];
        $orderId = DB::table($this->paymentOrderTable)->insertGetId($paymentOrderData);

        $orderInfo = DB::table($this->paymentOrderTable)->where('id', $orderId)->first();
        $orderInfo->product_id = $productId;
        $this->pay($orderInfo);
        // return $orderInfo->product_name;
    }

    private function pay($orderInfo)
    {
        header("Content-type:text/html;charset=utf-8");
        //页面编码要与参数inputCharset一致，否则服务器收到参数值中的汉字为乱码而导致验证签名失败。
        $serverUrl = config('netPay.SERVERURL');

        $orderid = $orderInfo->id;
        $trxamt = ($orderInfo->order_price) * 100;
        $goodsid = $orderInfo->product_id;
        $goodsinf = $orderInfo->product_name . '购买';
        $returl = config('app.url') . $this->returl;
        $notifyurl = config('app.url') . $this->notifyurl;
        $validtime = 10; //有效支付时间
        $gateid = '';

        $cusid = config('netPay.CUSID');
        $appid = config('netPay.APPID');
        $charset = config('netPay.CHARSET');
        $randomstr = md5(uniqid(microtime(true), true));

        // 生成签名字符串。
        $params = array();
        $params["cusid"] = $cusid;
        $params["appid"] = $appid;
        $params["charset"] = $charset;
        $params["returl"] = $returl;
        $params["notifyurl"] = $notifyurl;
        $params["goodsid"] = $goodsid;
        $params["goodsinf"] = $goodsinf;
        $params["trxamt"] = $trxamt;
        $params["orderid"] = $orderid;
        $params["randomstr"] = $randomstr;
        $params["gateid"] = $gateid;
        $params["validtime"] = $validtime;

        $signMsg = AppUtil::SignArray($params, config('netPay.APPKEY'));

        $params['key'] = config('netPay.APPKEY');
        ksort($params);

        $str = '<form name="form2" action="' . $serverUrl . '" method="post" id="netPay">
        <input type="hidden" name="cusid" id="cusid" value="' . $cusid . '" />
        <input type="hidden" name="appid" id="appid" value="' . $appid . '"/>
        <input type="hidden" name="charset" id="charset" value="' . $charset . '" />
        <input type="hidden" name="returl" id="returl" value="' . $returl . '"/>
        <input type="hidden" name="notifyurl" id="notifyurl" value="' . $notifyurl . '" />
        <input type="hidden" name="goodsid" id="goodsid" value="' . $goodsid . '"/>
        <input type="hidden" name="goodsinf" id="goodsinf" value="' . $goodsinf . '" />
        <input type="hidden" name="trxamt" id="trxamt" value="' . $trxamt . '"/>
        <input type="hidden" name="orderid" id="orderid" value="' . $orderid . '" />
        <input type="hidden" name="randomstr" id="randomstr" value="' . $randomstr . '" />
        <input type="hidden" name="gateid" id="gateid" value="' . $gateid . '" />
        <input type="hidden" name="validtime" id="validtime" value="' . $validtime . '"/>


        <input type="hidden" name="sign" id="sign" value="' . $signMsg . '" />
        <div align="center"><input type="submit" value="pay" align=center/></div>
        <!--================= post 方式提交支付请求 end =====================-->
        <script>var form = document.getElementById(\'netPay\');form.submit();</script>
    </form>
    </body>
    </html>';
        echo $str;
    }

    public function ret()
    {
        $paymentUrl = 'https://baidu.com';
        if ($this->verify($_POST)) {
            $this->updatePayment($_POST);
        }
        return redirect($paymentUrl);
    }

    public function notify()
    {
        if ($this->verify($_POST)) {
            $this->updatePayment($_POST);
        }
        echo "success";
    }

    private function verify($post)
    {
        $params = array();
        foreach ($post as $key => $val) {
            $params[$key] = $val;
        }
        if (count($params) < 1) {
            return false;
        }
        if (AppUtil::ValidSign($params, config('netPay.APPKEY')) && $post['trxstatus'] == '0000') {
            return true;
        }
    }

    private function updatePayment($post)
    {
        $data['payment_time'] = date("Y-m-d H:i:s");
        $data['status'] = 2;
        $data['trxid'] = $post['trxid'];
        DB::table($this->paymentOrderTable)
            ->where('id', $post['cusorderid'])
            ->update($data);
    }
}